package com.ksc.storekeeper.client.presenter;

import java.util.List;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.TabData;
import com.gwtplatform.mvp.client.TabDataBasic;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.TabInfo;
import com.gwtplatform.mvp.client.annotations.TitleFunction;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace;
import com.ksc.storekeeper.client.handlers.PlaceChangeHandler;
import com.ksc.storekeeper.client.mvp.NameTokens;
import com.ksc.storekeeper.client.mvp.StoreKeeperGinInjector;
import com.ksc.storekeeper.client.presenter.StoreItemsPresenter.StoreItemsProxy;
import com.ksc.storekeeper.client.view.StoreItemsView;
import com.ksc.storekeeper.shared.dto.ProductDTO;
import com.ksc.storekeeper.shared.rpc.ProductServiceAsync;

public class StoreItemsPresenter extends Presenter<StoreItemsView, StoreItemsProxy> implements PlaceChangeHandler {

	@Inject
	ProductServiceAsync productServiceAsync;
	
	@Inject
	PlaceManager placeManager;
	
	@Inject
	public StoreItemsPresenter(EventBus eventBus, StoreItemsView view, StoreItemsProxy proxy) {
		super(eventBus, view, proxy);
		getView().setPlaceChangeHandler(this);
	}

	@ProxyCodeSplit
	@NameToken(NameTokens.ITEMS_STORE)
	public interface StoreItemsProxy extends TabContentProxyPlace<StoreItemsPresenter> {

	}

	@TabInfo(container = MyStorePresenter.class)
	static TabData getTabLabel(StoreKeeperGinInjector ginjector) {
		return new TabDataBasic(ginjector.getStoreKeeperConstants().items(), 0);
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, MyStorePresenter.TYPE_SetTabContent, this);
	}	
	
	@Override
	protected void onReveal() {
		super.onReveal();
		productServiceAsync.getAllProducts(new AsyncCallback<List<ProductDTO>>() {
			
			@Override
			public void onSuccess(List<ProductDTO> result) {
				getView().addProducts(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				getView().setStatus(caught.getMessage());
				caught.printStackTrace();
			}
		});
	}

	@TitleFunction
	public String getTranslatedTitle(StoreKeeperGinInjector gInjector) {
		return gInjector.getStoreKeeperConstants().items();
	}

	@Override
	public void changePlace(String token,String name,String value) {
		PlaceRequest pR = new PlaceRequest(token);
		placeManager.revealPlace(pR.with(name, value));
		
	}
}
